

package yf.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.yf.response.RRException;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.LotteryActStatusEnum;
import yf.mall.enums.LotteryRecordStatusEnum;
import yf.mall.enums.MallActStatusEnum;
import yf.mall.vo.LotteryActVo;
import yf.mall.vo.down.LotteryRecordDown;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

import yf.mall.vo.LotteryRecordVo;
import yf.mall.service.LotteryRecordService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Thu Aug 20 11:07:03 CST 2020
 */
@Service
public class LotteryRecordServiceImpl extends BaseServiceImpl<LotteryRecordEntity> implements LotteryRecordService {

    private LotteryRecordDao dao;


    @Autowired
    public void setDao(LotteryRecordDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }


    @Override
    public List<LotteryRecordVo> findVo(LotteryRecordVo vo) {
        return dao.findVo(vo);
    }

    @Override
    public LotteryRecordVo getVo(Long id) {
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(LotteryRecordVo vo) {
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(LotteryRecordVo vo) {
        return dao.update(vo.getEntity());
    }


    @Override
    public void downLoad(HttpServletResponse response, List<LotteryRecordVo> list) {
        try {
            List<LotteryRecordDown> datas = list.stream().map(item -> new LotteryRecordDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), LotteryRecordDown.class).sheet("模板").doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal totalActIdAndGoodId(Long actId, Long goodsId, Long userId) {
        Integer totalAct = this.dao.totalActIdAndGoodsId(actId, null);
        Integer totalGoods = this.dao.totalActIdAndGoodsId(actId, goodsId);
        BigDecimal divide = BigDecimal.ZERO;
        if (totalGoods > 0 && totalAct > 0) {
            divide = new BigDecimal(totalGoods).divide(new BigDecimal(totalAct), 8, BigDecimal.ROUND_HALF_UP);
        }
        return divide;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<LotteryRecordEntity> findByUserId(Long userId, int page, int limit) {
        PageHelper.startPage(page, limit).setOrderBy(" time desc");
        return this.dao.findByUserIdIsLottery(userId, LotteryRecordStatusEnum.LOTTERY.getIndex());
    }

    @Autowired
    private LotteryActDao lotteryActDao;

    /**
     * 获取所有的抽奖记录
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<LotteryRecordEntity> allLotteryInfo(Long userId) {
        //获取所有已经开始的活动
        List<LotteryActEntity> actEntities = this.lotteryActDao.findByStatusAndToday(LotteryActStatusEnum.OPEN.getIndex(), new Date());
        LotteryActEntity lotteryActEntity = null;
        if (actEntities != null && actEntities.size() > 0) {
            lotteryActEntity = actEntities.get(0);
        } else {
            List<LotteryActEntity> list = this.lotteryActDao.findByToday(new Date());
            if (list != null && list.size() > 0) {
                for (LotteryActEntity actEntity : list) {
                    if (actEntity != null && actEntity.getStartTime() != null) {
                        SimpleDateFormat smp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        throw new RRException("活动未开始,将于" + smp.format(actEntity.getStartTime()) + "开始");
                    }
                }
            } else {
                throw new RRException("没有抽奖活动");
            }
        }
        List<LotteryRecordEntity> recordEntities = this.dao.findByUserId(userId,lotteryActEntity.getId());
        List<LotteryRecordEntity> recordEntityList = new ArrayList<>();

        // 设置记录的价格，订单名字
        for (LotteryRecordEntity recordEntity : recordEntities) {
            String name = "";
            BigDecimal price = BigDecimal.ZERO;
            if (recordEntity.getOrderNo() != null) {
                MallOrderEntity orderEntity = mallOrderDao.findByOrderNo(recordEntity.getOrderNo());
                if (orderEntity != null) {
                    if (orderEntity.getShopId() != null) {
                        ShopEntity shopEntity = shopDao.get(orderEntity.getShopId());
                        if (shopEntity != null && shopEntity.getName() != null) {
                            recordEntity.setShopName(shopEntity.getName());
                        }
                    }
                    List<OrderItemEntity> itemEntities = orderItemDao.findByOrderId(orderEntity.getId());
                    if (itemEntities != null && itemEntities.size() > 0) {
                        for (OrderItemEntity itemEntity : itemEntities) {
                            if (itemEntity != null) {
                                MallActEntity actEntity = mallActDao.findByGoodsIdAndstatus(itemEntity.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
                                if (actEntity != null && actEntity.getBindLotteryId() != null) {
                                    name = name +"&&"+ itemEntity.getName() + "*" + itemEntity.getQuantity();
                                    price = price.add(itemEntity.getPrice().multiply(BigDecimal.valueOf(itemEntity.getQuantity())));
                                }
                            }
                        }
                    }


                }
            }
            if (recordEntity.getIsLottery() != null && recordEntity.getIsLottery().equals(LotteryRecordStatusEnum.NOT_LOTTERY.getIndex())) {
                recordEntity.setGoodsName(null);
                recordEntity.setGoodsId(null);
                recordEntity.setBandGoodsId(null);
            }
            recordEntity.setPrice(price);
            recordEntity.setOrderName(name);
            recordEntityList.add(recordEntity);
        }
        return recordEntityList;
    }

    @Autowired
    private MallOrderDao mallOrderDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private MallActDao mallActDao;
    @Autowired
    private MallGoodsDao mallGoodsDao;

    @Autowired
    private ShopDao shopDao;
}
